<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="dictionaryTypes" highlight-current-row v-loading="listLoading"
				  @selection-change="selsChange"
				  @row-dblclick="showDrawer"
				  style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="类型编号" width="320" sortable>
			</el-table-column>
			<el-table-column prop="name" label="类型名称" width="320" sortable>
			</el-table-column>
			<el-table-column label="操作" width="350">
				<template scope="scope">
					<el-button size="small" @click="handleDictionaryType(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

        <!--类型详情抽屉-->
		<el-drawer
				:title="typeName"
				:visible.sync="dictionaryDetailDrawerVisible"
				direction="rtl"
				size="50%">
            <!--类型详情工具条 高级查询和添加-->
            <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
                <el-form :inline="true" :model="detailFilters">
                    <el-form-item>
                        <el-input v-model="detailFilters.keyword" placeholder="关键字"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" v-on:click="searchDetail">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleDetailAdd">新增</el-button>
                    </el-form-item>
                </el-form>
            </el-col>

            <!--类型详情展示列表-->
			<el-table :data="details"
                      highlight-current-row v-loading="detailListLoading"
                      @selection-change="selsDetailChange"
                      style="width: 100%;">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column type="index" width="60"></el-table-column>
				<el-table-column property="name" label="类型详情" width="120"></el-table-column>
				<el-table-column property="types_id" label="父级id" width="120"></el-table-column>
                <el-table-column label="操作" width="350">
                    <template scope="scope">
                        <el-button size="small" @click="handleDictionaryDetail(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDetailDel(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
			</el-table>

            <!--数据字典类型详情的编辑和修改界面-->
            <!--:close-on-click-modal：是否可以通过点击 modal即模态框周围的模糊区域关闭 Dialog
                @close：模态框关闭事件的回调
                :visible.sync：是否显示 Dialog，支持 .sync 修饰符
                prop="sn" 如果要校验数据必须有此声明
                append-to-body="true"  Dialog 自身是否插入至 body 元素上。嵌套的 Dialog 必须指定该属性并赋值为 true
                -->
            <el-dialog :title="title"
                       :visible.sync="dictionaryDetailFormVisible"
                       @close="closeDetailDialog"
                       :append-to-body="true"
                       :close-on-click-modal="false">
                <el-form :model="dictionaryDetailForm" label-width="80px" :rules="dictionaryDetailFormRules" ref="dictionaryDetailForm">

                    <!--prop表单域 model 字段，在使用 validate、resetFields 方法的情况下，该属性是必填的,用于数据校验-->
                    <el-form-item :label="typeName"  prop="name">
                        <el-input v-model="dictionaryDetailForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="父级类型" v-show="false" prop="name">
                        <el-input v-model="dictionaryDetailForm.types_id"  auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button  @click="closeDetailForm()">取消</el-button>
                    <el-button type="primary" @click.native="dictionaryDetailSubmit" :loading="dictionaryDetailLoading">提交</el-button>
                </div>
            </el-dialog>

            <!--类型详情工具条 批量删除和分页-->
            <el-col :span="24" class="toolbar">
                <el-button type="danger" @click="batchDetailRemove" :disabled="this.detailSels.length===0">批量删除</el-button>
                <!--:current-page="page" 处理当前页面已经跳转，但仍然显示之前的页面状态的bug-->
                <el-pagination layout="prev, pager, next"
                               @current-change="handleDetailCurrentChange"
                               :current-page="detailPage"
                               :page-size="detailPageSize"
                               :total="detailTotal"
                               style="float:right;">
                </el-pagination>
            </el-col>
		</el-drawer>
        <!--抽屉结束-->

		<!--工具条 批量删除和分页-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<!--:current-page="page" 处理当前页面已经跳转，但任然显示之前的页面状态的bug-->
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :current-page="page"
						   :page-size="pageSize"
						   :total="total"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--数据字典类型编辑和修改界面-->
		<!--:close-on-click-modal：是否可以通过点击 modal即模态框周围的模糊区域关闭 Dialog
			@close：模态框关闭事件的回调
			:visible.sync：是否显示 Dialog，支持 .sync 修饰符
            prop="sn" 如果要校验数据必须有此声明
			-->
		<el-dialog :title="title" :visible.sync="dictionaryTypeFormVisible" @close="closeDialog"  :close-on-click-modal="false">
			<el-form :model="dictionaryTypeForm" label-width="80px" :rules="dictionaryTypeFormRules" ref="dictionaryTypeForm">
				<el-form-item label="类型编号" prop="sn">
					<el-input v-model="dictionaryTypeForm.sn" auto-complete="off"></el-input>
				</el-form-item>
                <!--prop表单域 model 字段，在使用 validate、resetFields 方法的情况下，该属性是必填的,用于数据校验-->
                <el-form-item label="类型名称"  prop="name">
                    <el-input v-model="dictionaryTypeForm.name" auto-complete="off"></el-input>
                </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button  @click="closeForm('dictionaryTypeForm')">取消</el-button>
				<el-button type="primary" @click.native="dictionaryTypeSubmit" :loading="dictionaryTypeLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDictionaryTypeListPage, removeDictionaryType, batchRemoveDictionaryType, dictionaryTypeDictionaryType, addDictionaryType } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
                    keyword: ''
				},
				dictionaryTypes: [],

				total: 0,
				page: 1,
                title:'',
                pageSize: 10,
				listLoading: false,
				sels: [],//列表选中列

				dictionaryTypeFormVisible: false,//编辑界面是否显示
				dictionaryTypeLoading: false,
                dictionaryDetailDrawerVisible: false,
				dictionaryTypeFormRules: {
                    sn: [
                        { required: true, message: '请输类型编码', trigger: 'blur' }
                    ],
					name: [
						{ required: true, message: '请输入类型名', trigger: 'blur' }
					]

				},
				// 数据字典类型表单数据
				dictionaryTypeForm: {
					id: 0,
                    sn: '',
					name: '',
				},
            //=========以下是类型详情展示抽屉页面的相关数据==============
                detailFilters: {
                    detailKeyword: ''
                },
                type_id: 1,
                typeName: '',
                details: [],
                detailTotal: 0,
                detailPage: 1,
                detailPageSize: 5,
                detailListLoading: false,
                detailSels: [],//列表选中列

                dictionaryDetailFormVisible: false,//编辑添加模态框是否显示
                dictionaryDetailLoading: false,
                dictionaryDetailFormRules: {
                    name: [
                        { required: true, message: '请输入类型详情', trigger: 'blur' }
                    ]

                },

                dictionaryDetailForm: {
                    id: 0,
                    name: '',
                    types_id: 0
                }
			}
		},
		methods: {

            // ===========================类型详情抽屉页面的相关方法=========================
            //获取每行类型的详情列表
            showDrawer(row) {
                this.detailPage = 1;
                this.dictionaryDetailDrawerVisible = true;
                this.type_id = row.id;
                this.typeName = row.name;
                this.getDictionaryDetails();
            },
            // 页面改变重查分页数据
            handleDetailCurrentChange(val) {
                this.detailPage = val;
                this.getDictionaryDetails();

            },
            //获取数据字典类型列表
            getDictionaryDetails() {
                let para = {
                    keyword: this.detailFilters.keyword,
                    pageSize: this.detailPageSize,
                    currentPage: this.detailPage,
                    type_id: this.type_id
                };
                this.detailListLoading = true;
                // 向后台发送请求获取值
                this.$http.post("/dicdetail",para)
                    .then(result=>{
                        console.log(result);
                        // 请求成功就从返回参数中取值赋给双向绑定的dictionaryTypes，而值得变动会使页面重新加载渲染
                        this.details = result.data.list;
                        // console.log(this.dictionaryTypes);
                        this.detailTotal = result.data.total;
                        // 关闭页面数据加载特效
                        this.detailListLoading = false;
                    })
                    .catch(result=>{
                        alert("系统错误！！！");
                    })

            },

            //删除
            handleDetailDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.detailListLoading = true;
                    //NProgress.start();
                    let para = { id: row.id };
                    this.$http.delete("/dicdetail/"+para.id)
                        .then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
                            }
                            this.detailListLoading = false;// 关闭忙等框
                            this.detailPage = 1;// 重新定位到第一页
                            this.getDictionaryDetails();// 重新加载数据
                        })
                        .catch(result => { // 失败了也要定位到第一页
                            this.detailListLoading = false;// 关闭忙等框
                            alert(result.data.message);
                        });
                }).catch(() => {
                });
            },

            //显示编辑界面
            handleDictionaryDetail: function (index, row) {
                this.title = "编辑"
                this.dictionaryDetailFormVisible = true;
                this.dictionaryDetailForm = Object.assign({}, row);// 克隆当前行数据用于回显
            },

            //显示新增界面
            handleDetailAdd: function () {

                this.title = "添加"
                this.dictionaryDetailFormVisible = true;
                this.dictionaryDetailForm = {// 清空模态框的数据
                    id: null,
                    name: '',
                    types_id: this.type_id
                };
            },
            //编辑
            dictionaryDetailSubmit: function () {
                // validate（）方法可以检验整个表单，可以传入两个参数：第一个是是否校验成功和，第二个是未通过校验的字段。只写一个默认是是否校验成功
                this.$refs.dictionaryDetailForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.dictionaryDetailLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.dictionaryDetailForm);
                            // console.log(para);
                            this.$http.put("/dicdetail",para)
                                .then(result=>{
                                    if(result.data.success){
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                    } else {
                                        this.$message({
                                            message: '提交失败',
                                            type: 'error'
                                        });
                                    }
                                    this.dictionaryDetailLoading = false;
                                    this.dictionaryDetailFormVisible = false;
                                    this.getDictionaryDetails();

                                })
                                .catch(result=>{
                                    this.dictionaryDetailLoading = false;
                                })
                        });
                    }
                });
            },
            selsDetailChange: function (sels) {// 每选中一行都会把该行的数据添加到sels
                this.detailSels = sels;
                // console.log(sels);
            },
            //批量删除
            batchDetailRemove: function () {
                // 遍历每行数据取出id聚合为一个id的数组
                var ids = this.detailSels.map(item => item.id);
                // console.log(ids);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.detailListLoading = true;
                    //NProgress.start();
                    let para = { ids: ids };
                    this.$http.patch("/dicdetail/dictionaryDetail",para.ids)
                        .then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
                            }
                            this.detailListLoading = false;// 关闭忙等框
                            this.detailPage = 1;// 重新定位到第一页
                            this.getDictionaryDetails();// 重新加载数据
                        })
                        .catch(result => { // 失败了也要定位到第一页
                            this.detailListLoading = false;// 关闭忙等框
                            alert("系统错误");
                        });

                }).catch(() => {
                });
            },
            searchDetail(){// 解决在除首页外的页面上，高级查询无效的bug，原因是翻页后如果不跳回首页就高级查询，
                // 而后端使用了limit，会从当前页-1再*查询的条数开始查询，如果查询结果没有这么多条那么返回结果为空
                this.detailPage = 1;
                this.getDictionaryDetails();
            },
            closeDetailDialog(){
                this.$refs['dictionaryDetailForm'].resetFields();
            },
            closeDetailForm(){
                this.dictionaryDetailFormVisible = false;
                this.$refs['dictionaryDetailForm'].resetFields();

            },

		    //=================数据字典类型相关方法==================
		    // 页面改变重查分页数据
			handleCurrentChange(val) {
				this.page = val;
				this.getDictionaryTypes();
			},
			//获取数据字典类型列表
			getDictionaryTypes() {
				let para = {
                    keyword: this.filters.keyword,
                    pageSize:this.pageSize,
                    currentPage:this.page
				};
				// console.log(para);
				this.listLoading = true;
				// 向后台发送请求获取值
				this.$http.post("/dictype",para)
					.then(result=>{
                        console.log(result);
					   	// 请求成功就从返回参数中取值赋给双向绑定的dictionaryTypes，而值得变动会使页面重新加载渲染
					    this.dictionaryTypes = result.data.list;
                        // console.log(this.dictionaryTypes);
					    this.total = result.data.total;
					    // 关闭页面数据加载特效
                        this.listLoading = false;
					})
					.catch(result=>{
						alert("系统错误！！！");
					})

			},

			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					this.$http.delete("/dictype/"+para.id)
						.then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
							} else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
							}
                            this.listLoading = false;// 关闭忙等框
							this.page = 1;// 重新定位到第一页
                            this.getDictionaryTypes();// 重新加载数据
						})
	                        .catch(result => { // 失败了也要定位到第一页
                            this.listLoading = false;// 关闭忙等框
                            alert(result.data.message);
                        });
				}).catch(() => {
				});
			},

			//显示编辑界面
			handleDictionaryType: function (index, row) {
                this.title = "编辑"
				this.dictionaryTypeFormVisible = true;
				this.dictionaryTypeForm = Object.assign({}, row);// 克隆当前行数据用于回显
			},

			//显示新增界面
            handleAdd: function () {

			    this.title = "添加"
				this.dictionaryTypeFormVisible = true;
				this.dictionaryTypeForm = {// 清空模态框的数据
                    id: null,
                    sn: '',
                    name: '',
				};
			},
			//编辑
			dictionaryTypeSubmit: function () {
                // validate（）方法可以检验整个表单，可以传入两个参数：第一个是是否校验成功和，第二个是未通过校验的字段。只写一个默认是是否校验成功
				this.$refs.dictionaryTypeForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.dictionaryTypeLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.dictionaryTypeForm);

							// console.log(para);
							this.$http.put("/dictype",para)
                                .then(result=>{
                                    if(result.data.success){
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                    } else {
                                        this.$message({
                                            message: '提交失败',
                                            type: 'error'
                                        });
                                    }
                                    this.dictionaryTypeLoading = false;
                                    this.dictionaryTypeFormVisible = false;
                                    this.getDictionaryTypes();

                                })
                                .catch(result=>{
                                    this.dictionaryTypeLoading = false;
                                })
						});
					}
				});
			},
			selsChange: function (sels) {// 每选中一行都会把该行的数据添加到sels
				this.sels = sels;
				// console.log(sels);
			},
			//批量删除
			batchRemove: function () {
                // 遍历每行数据取出id聚合为一个id的数组
                var ids = this.sels.map(item => item.id);
                // console.log(ids);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					this.$http.patch("/dictype/dictionaryType",para.ids)
                        .then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
                            }
                            this.listLoading = false;// 关闭忙等框
                            this.page = 1;// 重新定位到第一页
                            this.getDictionaryTypes();// 重新加载数据
                        })
                        .catch(result => { // 失败了也要定位到第一页
                            this.listLoading = false;// 关闭忙等框
                            alert("系统错误");
                        });

				}).catch(() => {
				});
			},
			search(){// 解决在除首页外的页面上，高级查询无效的bug，原因是翻页后如果不跳回首页就高级查询，
				// 而后端使用了limit，会从当前页-1再*查询的条数开始查询，如果查询结果没有这么多条那么返回结果为空
			    this.page = 1;
			    this.getDictionaryTypes();
			},
            closeDialog(){
                this.$refs['dictionaryTypeForm'].resetFields();
			},
            closeForm(){
                this.dictionaryTypeFormVisible = false;
                this.$refs['dictionaryTypeForm'].resetFields();

            }



		},
		mounted() {
			this.getDictionaryTypes();

		}
	}

</script>

<style scoped>

</style>